# -*- coding:utf-8 -*-

from sklearn.datasets import load_iris,load_boston
from sklearn.feature_selection import VarianceThreshold
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression,SGDRegressor,Ridge
from sklearn.metrics import mean_squared_error
import joblib
import pandas as pd
import numpy as np
import sys
import pypinyin
sys.path.append("../")
from frameworks.utils.PadasExcelUtil import *
import re
import nums_from_string
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.decomposition import PCA
from scipy.stats import pearsonr
from services.CodesService import *

def main():
    # 1）获取数据
    codeService = CodeService();
    data = codeService.getKlineDay();

    df = pd.DataFrame(data)
    print("特征数量：\n", df.shape)

    """
    # 2、实例化一个转换器类
    transfer = VarianceThreshold(threshold=10)

    data = df.iloc[:,:]

    print("data:\n", data)

    # 3、调用fit_transform
    data_new = transfer.fit_transform(data)
    print("data_new:\n", data_new, data_new.shape)

    # 计算某两个变量之间的相关系数
    r1 = pearsonr(data["最高"], data["最低"])
    print("radio与earn之间的相关性：\n", r1)
    """

    df['zf'] = df.apply(lambda row: 0 if float(((row["close"]-row["pre_close"])*100)/row["close"]) > 0.1 else 1, axis = 1)
    df['code'] = df.apply(lambda row: row['code'].replace("SH", "").replace("SZ",""), axis=1)

    newdf = df[['exchange', 'all_money']]

    # 2）划分数据集
    x_train, x_test, y_train, y_test = train_test_split(newdf, df["zf"], random_state=22)

    # 3）标准化
    transfer = StandardScaler()
    x_train = transfer.fit_transform(x_train)
    x_test = transfer.transform(x_test)

    #4）预估器
    estimator = RandomForestClassifier()
    # 加入网格搜索与交叉验证
    # 参数准备
    param_dict = {"n_estimators": [120, 200, 300, 500, 800, 1200], "max_depth": [5, 8, 15, 25, 30]}
    #param_dict = {"n_estimators": [300], "max_depth": [8]}
    estimator = GridSearchCV(estimator, param_grid=param_dict, cv=3)
    estimator.fit(x_train, y_train)

    # 保存模型
    #joblib.dump(estimator, "my_ridge.pkl")
    # 加载模型
    #estimator = joblib.load("my_ridge.pkl")

    # 5）得出模型
    #print("岭回归-权重系数为：\n", estimator.coef_)
    #print("岭回归-偏置为：\n", estimator.intercept_)

    # 5）模型评估
    # 方法1：直接比对真实值和预测值
    y_predict = estimator.predict(x_test)
    print(y_predict)

    # 方法2：计算准确率
    score = estimator.score(x_test, y_test)
    print("准确率为：\n", score)

    # 最佳参数：best_params_
    print("最佳参数：\n", estimator.best_params_)
    # 最佳结果：best_score_
    print("最佳结果：\n", estimator.best_score_)
    # 最佳估计器：best_estimator_
    print("最佳估计器:\n", estimator.best_estimator_)
    # 交叉验证结果：cv_results_
    print("交叉验证结果:\n", estimator.cv_results_)

if __name__ == "__main__":
    main()